<?php

declare(strict_types=1);

namespace App\CustHub\Model;

use App\Common\Constants\ErrorCode;
use App\Exception\BusinessException;
use Mine\MineModel;

/**
 * @property int $id 
 * @property int $main_uid 
 * @property int $uid 
 * @property int $cs_id 客服ID
 * @property int $p_id 父id
 * @property int $sort 
 * @property int $is_personal 1个人 0企业
 * @property string $title 
 * @property \Carbon\Carbon $created_at 创建时间
 * @property \Carbon\Carbon $updated_at 更新时间
 */
class ChWordGroup extends MineModel
{
    /**
     * The table associated with the model.
     */
    protected ?string $table = 'ch_word_group';

    /**
     * The attributes that are mass assignable.
     */
    protected array $fillable = ['id', 'main_uid', 'uid', 'cs_id', 'p_id', 'sort', 'is_personal', 'title', 'created_at', 'updated_at'];

    /**
     * The attributes that should be cast to native types.
     */
    protected array $casts = ['id' => 'integer', 'main_uid' => 'integer', 'uid' => 'integer', 'cs_id' => 'integer', 'p_id' => 'integer', 'sort' => 'integer', 'is_personal' => 'integer', 'created_at' => 'datetime', 'updated_at' => 'datetime'];

    protected array $appends = [];

    public static function saveGroup($uid,$main_uid,$title,$is_personal,$pId = 0,$id = 0)
    {
        $model = new self();
        if($id){
            $model = self::where('id',$id) -> first();
            if(empty($model)) throw new BusinessException(ErrorCode::NOT_ISSET,'数据不存在');
        }else{
            $model -> sort = self::query() -> max('sort') + 1;
        }
        $model -> uid = $uid;
        $model -> title = $title;
        $model -> main_uid = $main_uid;
        $model -> p_id = !empty($pId)?$pId:0;
        $model -> is_personal = $is_personal;
        $model -> save();
        return $model;
    }
}
